﻿/*
 * Copyright (c) 2015-2016 Constantijn Evenhuis (blueprints@const.nl)
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;

namespace Blueprints
{
    /// <summary>
    /// Provides a set of extension methods for Uris.
    /// </summary>
    public static class UriExtensions
    {
        /// <summary>
        /// The file:// scheme.
        /// </summary>
        public const string UriSchemeFile = "file";
        
        /// <summary>
        /// The http:// scheme.
        /// </summary>
        public const string UriSchemeHttp = "http";
        
        /// <summary>
        /// The https:// scheme.
        /// </summary>
        public const string UriSchemeHttps = "https";

        /// <summary>
        /// The ftp:// scheme.
        /// </summary>
        public const string UriSchemeFtp = "ftp";

        private static readonly Dictionary<string, MediaType> mediaTypes = new Dictionary<string, MediaType>(StringComparer.Ordinal)
        {
            { "application/xml", MediaType.Xml },
            { "text/xml", MediaType.Xml },
            { "application/json", MediaType.Json },
        };

        private static readonly Dictionary<string, MediaType> extensions = new Dictionary<string, MediaType>(StringComparer.OrdinalIgnoreCase)
        {
            { ".xml", MediaType.Xml },
            { ".json", MediaType.Json },
        };

        /// <summary>
        /// Gets the media type of <paramref name="uri"/> by inspecting its file name.
        /// </summary>
        /// <param name="uri">The uri for which to get the text format.</param>
        /// <returns>The media type of the uri.</returns>
        public static MediaType GetMediaType(this Uri uri)
        {
            string path = uri.GetComponents(UriComponents.Path, UriFormat.SafeUnescaped);
            int dotIndex = path.LastIndexOf('.');
            if (dotIndex < 0)
            {
                return MediaType.Unknown;
            }

            MediaType mediaType;
            if (!extensions.TryGetValue(path.Substring(dotIndex), out mediaType))
            {
                return MediaType.Unknown;
            }

            return mediaType;
        }

        /// <summary>
        /// Gets the base uri, without a fragment, from <paramref name="uri"/> which may contain a fragment.
        /// </summary>
        /// <param name="uri">The uri for which to get the base uri.</param>
        /// <returns>The base uri.</returns>
        public static Uri GetBaseUri(this Uri uri)
        {
            UriBuilder builder = new UriBuilder(uri);
            builder.Fragment = null;
            return builder.Uri;
        }

        /// <summary>
        /// Gets the fragment component from an uri.
        /// </summary>
        /// <param name="uri">The uri from which to get the fragment.</param>
        /// <returns>The fragment component, without leading pound sign.</returns>
        public static string GetFragment(this Uri uri)
        {
            return uri.GetComponents(UriComponents.Fragment, UriFormat.Unescaped);
        }

        /// <summary>
        /// Ensures that a file uri can be used to make relative uri's with fragments.
        /// </summary>
        /// <param name="uri">The uri to prepare.</param>
        /// <returns>The prepared uri.</returns>
        public static Uri PrepareUri(this Uri uri)
        {
            if (!uri.Scheme.Equals(UriSchemeFile, StringComparison.OrdinalIgnoreCase))
            {
                return uri;
            }

            if (uri.OriginalString.StartsWith(UriSchemeFile, StringComparison.OrdinalIgnoreCase))
            {
                return uri;
            }

            return new Uri(uri.AbsoluteUri);
        }

        /// <summary>
        /// Gets a stream to the contents of <paramref name="uri"/>.
        /// </summary>
        /// <param name="uri">The uri from which to read.</param>
        /// <param name="mediaType">The media type indicated by the uri.</param>
        /// <returns>A stream to the contents of <paramref name="uri"/>.</returns>
        public static Stream GetStream(this Uri uri, out MediaType mediaType)
        {
            mediaType = uri.GetMediaType();
            string scheme = uri.Scheme;
            if (!scheme.Equals(UriSchemeHttp, StringComparison.OrdinalIgnoreCase)
                && !scheme.Equals(UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
            {
                mediaType = uri.GetMediaType();
                throw new NotSupportedException("Unsupported Uri scheme: '" + uri.Scheme + "'");
            }

            WebRequest request = WebRequest.Create(uri);
            WebResponse response = request.EndGetResponse(request.BeginGetResponse(null, null));
            if (!mediaTypes.TryGetValue(response.ContentType, out mediaType))
            {
                mediaType = uri.GetMediaType();
            }

            return response.GetResponseStream();
        }
    }
}